/*
 * @Author       : 乐乐侠在此
 * @Date         : 2024-02-20 09:37:00
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2024-02-20 10:11:10
 * @Description  : 生产者消费者模型，producer是生产者，consumer是消费者
 */
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <deque>

using namespace std;

deque<int> g_dq;
condition_variable g_cv;
mutex mtx;

void producer()
{
    for (size_t i = 0; i < 10; i++)
    {
        {
            unique_lock<mutex> lock(mtx);
            // a tmp;
            g_dq.push_back(i);
            g_cv.notify_one();
            cout<<" * push task "<<i<<"yet"<<endl;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }
}

void consumer()
{
    while (1)
    {
        /* code */
        unique_lock<mutex> lock(mtx);
        g_cv.wait(lock, []() { return !g_dq.empty(); }); // g_cv 是条件变量，如果在条件变量的wait这里阻塞了，会释放掉wait的第一个参数，就是上一行的lock，直到其被notify
        int cur = g_dq.front();
        g_dq.pop_front();
         cout<<" ** get task "<<cur<<"yet"<<endl;
        // a tmp;
    }
}

int main()
{
    thread t1(producer);
    thread t2(consumer);
    t1.join();
    t2.join();
    return 0;
}